using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using LeisureCenter.Api;
using FMOD;

namespace FModPlayer
{
    public class FModAudioMedia : BaseFModMedia
    {
        protected override void CreateSoundIfNeeded()
        {
            if (sound == null)
            {
                CheckResult(player.FModSystem.createSound(FileName, MODE._2D | MODE.IGNORETAGS | MODE.NONBLOCKING /*| FMOD.MODE.HARDWARE*/ | MODE.MPEGSEARCH | FMOD.MODE.CREATESTREAM, ref sound));
            }
        }

        protected override void CreateChannelIfNeeded(bool paused)
        {
            if (channel == null)
            {
                uint percent = 0;
                bool starving = false;
                OPENSTATE state = OPENSTATE.ERROR;

                do
                {
                    CheckResult(sound.getOpenState(ref state, ref percent, ref starving));
                    switch (state)
                    {
                        case OPENSTATE.READY:
                            break;
                        case OPENSTATE.ERROR:
                            return;
                        default:
                            Thread.Sleep(10);
                            break;
                    }

                    CheckResult(player.FModSystem.playSound(CHANNELINDEX.FREE, sound, paused, ref channel));
                    base.CreateChannelIfNeeded(paused);
                }
                while (state != OPENSTATE.READY);
            }
        }

        protected override void DoStop()
        {
            if (this.channel != null)
                channel.setCallback(CHANNEL_CALLBACKTYPE.END, null, 0);
            base.DoStop();
        }

        public FModAudioMedia(FModPlayer player, string fileName)
            : base(player, fileName)
        {
        }

        #region IMedia implementation

        public override MediaKind Kind { get { return MediaKind.Music; } }

        public override void Preload()
        {
            CreateSoundIfNeeded();
            //CreateChannelIfNeeded(true);
        }

        #endregion
    }
}
